<template>
  <view class="app-layout">
    <app-header :title="tit" />
    <view class="app-main">
      <view class="goods-container" @click.prevent='handleClickOutside'>
        <view class="" style=" flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" style="height: 100%">
            <view class="step-nav">
              <view class="step-item" :class="{ active: currentStep === 1 }">
                第一步：填写基础信息
              </view>
              <view class="step-item" :class="{ active: currentStep === 2 }">
                第二步：填写商品详情
              </view>
            </view>

            <view class="form-container">
              <u-form labelPosition="left" labelWidth="90px" :model="formData" ref="refFrom">
                <template v-if="currentStep == 1">
                  <view class="info-tit"> 基本信息</view>
                  <view class="form-con">
                    <uni-row :gutter="40">
                      <uni-col :span="12">
                        <u-form-item label="商品编码">
                          <uni-easyinput :maxlength="8" clearable v-model="formData.spuId"
                            placeholder="不填写时，系统将默认生成商品SPU码" :disabled="spuId">
                            <template #right>
                              <text class="suffix-num">{{ (formData.spuId || '').length }}/8</text>
                            </template>
                          </uni-easyinput>
                        </u-form-item>
                      </uni-col>
                      <uni-col :span="12">
                        <u-form-item label="商品名称" required>
                          <uni-easyinput :maxlength="30" clearable v-model="formData.name" placeholder="请输入">
                            <template #right>
                              <text class="suffix-num">{{ (formData.name || '').length }}/30</text>
                            </template>
                          </uni-easyinput>
                        </u-form-item>
                      </uni-col>
                      <uni-col :span="12">
                        <u-form-item label="商品分类" required>
                          <uni-data-picker :localdata="range" popup-title="请选择" @change="onchange"
                            @nodeclick="onnodeclick" v-model="formData.categoryId"></uni-data-picker>
                        </u-form-item>
                      </uni-col>
                      <uni-col :span="12">
                        <u-row>
                          <view class="flex-label">
                            <u-form-item label="展示排序">
                              <uni-easyinput placeholder="请输入" type="number" clearable
                                v-model="formData.sortOrder"></uni-easyinput>
                            </u-form-item>
                          </view>


                          <view class="direction-container">
                            <view class="item" ref="tooltipContainer">
                              <image src="../../static/imgs/icon.png" mode="" class="icon-con"
                                @click.stop="toggleTooltip">
                              </image>
                              <view class="tooltip-box" :class="{ show: isTooltipShow }" ref="tooltipRef">
                                <view class="tooltip-content">商品的展示排序，数字越小，在商品列表、前台对应分类展示越靠前</view>
                                <view class="tooltip-arrow"></view>
                              </view>
                            </view>
                          </view>
                        </u-row>
                      </uni-col>
                      <uni-col :span="12">
                        <u-form-item label="发布场景" required>
                          <u-checkbox-group v-model="formData.sceneLabel" @change="checkboxChange">
                            <u-checkbox :customStyle="{ marginRight: '8px' }" label="门店自提" name="门店自提" />
                            <u-checkbox label="外卖配送" name="外卖配送" />
                          </u-checkbox-group>
                        </u-form-item>
                      </uni-col>
                      <uni-col :span="12">
                        <u-form-item label="配送方式">
                          <!-- <u-checkbox-group v-model="formData.deliveryMethod" @change="checkboxChange">
                        <u-checkbox shape="circle" label="商家配送" :name="0" />
                      </u-checkbox-group> -->
                          <u-radio-group v-model="formData.deliveryMethod">
                            <u-radio label="商家配送" :name="0" />
                          </u-radio-group>
                        </u-form-item>
                      </uni-col>
                      <!-- <uni-col :span="12">
                        <u-form-item label="制作时长">
                          <uni-easyinput placeholder="请输入" :maxlength="20" type="number" clearable
                            v-model="formData.productionTime">
                            <template #right>
                              <text class="suffix-txt">分钟</text>
                            </template>
                          </uni-easyinput>
                        </u-form-item>
                      </uni-col> -->
                      <uni-col :span="12">
                        <u-row>
                          <view class="flex-label">
                            <u-form-item label="制作时长">
                              <uni-easyinput placeholder="请输入" :maxlength="20" type="number" clearable
                                v-model="formData.productionTime">
                                <template #right>
                                  <text class="suffix-txt">分钟</text>
                                </template>
                              </uni-easyinput>
                            </u-form-item>
                          </view>


                          <view class="direction-container">
                            <view class="item">
                              <image src="../../static/imgs/icon.png" mode="" class="icon-con"
                                @click.stop="toggleTooltips">
                              </image>
                              <view class="tooltip-box" :class="{ show: isTooltipShows }" ref="tooltipRef">
                                <view class="tooltip-content">每一个商品的制作时常，用于计算订单制作时间</view>
                                <view class="tooltip-arrow"></view>
                              </view>
                            </view>
                          </view>
                        </u-row>
                      </uni-col>
                      <uni-col :span="12">
                        <u-form-item label="商品状态">
                          <u-radio-group v-model="formData.isPublished">
                            <u-radio :customStyle="{ marginRight: '8px' }" label="在售" :name="1" />
                            <u-radio label="下架" :name="0" />
                          </u-radio-group>
                        </u-form-item>
                      </uni-col>
                    </uni-row>
                  </view>
                  <view class="info-tit"> 价格设置 </view>
                  <view class="form-con">
                    <uni-row :gutter="40">
                      <uni-col :span="12">
                        <u-form-item label="商品规格">
                          <view class="specifications" @click="addSpecGroup"> 添加规格 </view>
                        </u-form-item>
                      </uni-col>
                      <!-- 无添加商品规格 -->
                      <template v-if="specGroups.length <= 0">

                        <uni-col :span="12">
                          <u-form-item label="零售价" required>
                            <uni-easyinput placeholder="请输入" type="digit" clearable v-model="formData.retailPrice">
                              <template #right>
                                <text class="suffix-txt">元</text>
                              </template>
                            </uni-easyinput>
                          </u-form-item>
                        </uni-col>
                        <uni-col :span="12">
                          <u-form-item label="市场价">
                            <uni-easyinput placeholder="请输入" type="digit" clearable v-model="formData.marketPrice">
                              <template #right>
                                <text class="suffix-txt">元</text>
                              </template>
                            </uni-easyinput>
                          </u-form-item>
                        </uni-col>
                        <uni-col :span="12">
                          <u-form-item label="成本价">
                            <uni-easyinput placeholder="请输入" type="digit" clearable v-model="formData.costPrice">
                              <template #right>
                                <text class="suffix-txt">元</text>
                              </template>
                            </uni-easyinput>
                          </u-form-item>
                        </uni-col>
                      </template>
                    </uni-row>
                    <uni-row>
                      <template v-if="specGroups.length > 0">
                        <view v-for="(group, groupIndex) in specGroups" :key="groupIndex" class="spec-group">
                          <view class="del-btn">
                            <u-button type="error" :plain="true" @click="removeSpecGroup(groupIndex)">- 删除规格</u-button>
                          </view>
                          <uni-row>
                            <uni-col :span="12">
                              <u-form-item label="规格名称">
                                <uni-easyinput placeholder="如：杯型、甜度" clearable v-model="group.specName"></uni-easyinput>
                              </u-form-item>
                            </uni-col>
                          </uni-row>

                          <uni-row>
                            <uni-col :span="24">
                              <u-form-item label="规格值">
                                <u-row>
                                  <u-tag v-for="(value, valueIndex) in group.specValues" plain :key="valueIndex"
                                    :text="value" size="medium" closable
                                    @close="removeSpecValue(groupIndex, valueIndex)"></u-tag>
                                  <uni-easyinput placeholder="请输入规格值" clearable
                                    v-model="group.tempValue"></uni-easyinput>
                                  <u-button type="primary" :plain="true" text="+ 添加规格值"
                                    :disabled="!group.tempValue.trim()" @click="addSpecValue(groupIndex)"></u-button>
                                </u-row>
                              </u-form-item>
                            </uni-col>
                          </uni-row>
                        </view>

                        <view class="generate-btn">
                          <view class="specifications" @click="generateSpecs"> 一键生成规格明细 </view>
                        </view>

                        <uni-row>
                          <uni-col :span="24">
                            <u-form-item label="规格明细">
                              <uni-row :gutter="10">
                                <uni-col :span="6">
                                  <uni-easyinput placeholder="零售价" type="digit" clearable v-model="batchRetail">
                                    <template #right>
                                      <text class="suffix-txt">元</text>
                                    </template>
                                  </uni-easyinput>
                                </uni-col>
                                <uni-col :span="6">
                                  <uni-easyinput placeholder="市场价" type="digit" clearable v-model="batchMarket">
                                    <template #right>
                                      <text class="suffix-txt">元</text>
                                    </template>
                                  </uni-easyinput>
                                </uni-col>
                                <uni-col :span="6">
                                  <uni-easyinput placeholder="成本价" type="digit" clearable v-model="batchCost">
                                    <template #right>
                                      <text class="suffix-txt">元</text>
                                    </template>
                                  </uni-easyinput>
                                </uni-col>
                                <uni-col :span="6">
                                  <u-button type="primary" :plain="true" text="批量填写" @click="batchFill"></u-button>
                                </uni-col>
                              </uni-row>
                            </u-form-item>
                          </uni-col>
                        </uni-row>
                        <uni-table border stripe emptyText="暂无更多数据" v-if="show">
                          <!-- 表头行 -->
                          <uni-tr>
                            <uni-th width="100" align="left" v-for="(group, gIndex) in specGroups"
                              :key="gIndex">{{ group.specName }}</uni-th>
                            <uni-th width="250" align="left">SKU编码</uni-th>
                            <uni-th width="150" align="left"><text class="start">
                                *</text>零售价</uni-th>
                            <uni-th width="150" align="left">市场价</uni-th>
                            <uni-th width="150" align="left">成本价</uni-th>
                            <uni-th align="left" width="100">操作</uni-th>
                          </uni-tr>
                          <!-- 表格数据行 -->
                          <uni-tr v-for="(row, rIndex) in specsRows" :key="rIndex">
                            <uni-td v-for="(group, gIndex) in specGroups" :key="gIndex">
                              {{ row.specValueDtoList.find((item) => item.name === group.specName)?.value }}
                            </uni-td>
                            <uni-td>
                              <uni-easyinput :maxlength="11" placeholder="不填写时，系统将默认生成商品SKU码" clearable
                                v-model="row.skuId" :disabled="spuId">
                                <template #right>
                                  <text class="suffix-num">{{ (row.skuId || '').length }}/11</text>
                                </template>
                              </uni-easyinput>
                            </uni-td>
                            <uni-td>
                              <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.retailPrice">
                                <template #right>
                                  <text class="suffix-txt">元</text>
                                </template>
                              </uni-easyinput>
                            </uni-td>
                            <uni-td>
                              <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.marketPrice">
                                <template #right>
                                  <text class="suffix-txt">元</text>
                                </template>
                              </uni-easyinput>
                            </uni-td>
                            <uni-td>
                              <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.costPrice">
                                <template #right>
                                  <text class="suffix-txt">元</text>
                                </template>
                              </uni-easyinput>
                            </uni-td>
                            <uni-td>
                              <u-icon name="trash" color="#EC3A4E" size="20" @click="delelGroups(rIndex)"></u-icon>
                            </uni-td>
                          </uni-tr>
                        </uni-table>
                      </template>
                    </uni-row>
                    <uni-row>
                      <uni-col :span="12">
                        <u-form-item label="商品属性">
                          <!-- <u-input placeholder="请输入" :maxlength="20" clearable v-model="formData.categoryName">
                        <template #suffix>
                          <text class="suffix-txt">元</text>
                        </template>
                      </u-input> -->
                          <view class="specifications" @click="addAttribute('1')"> +选择属性 </view>
                        </u-form-item>
                      </uni-col>
                    </uni-row>

                    <uni-row>
                      <uni-col :span="24" :offset="3" v-if="attributeList.length > 0">
                        <uni-row :gutter="20" v-for="(item, index) in attributeList" :key="index">
                          <uni-col :span="6">
                            <view class="goods-name"> 属性名称 </view>
                            <view class="row-bot">
                              <uni-easyinput v-model="item.name" disabled></uni-easyinput>
                            </view>
                          </uni-col>
                          <uni-col :span="18">
                            <view class="goods-name"> 属性值 </view>
                            <uni-row :gutter="20">
                              <view class="marg-col row-bot">
                                <uni-col :span="10" v-for="(ite,ind) in item.attributeValue" :key="ind">
                                  <uni-row :gutter="10">
                                    <uni-col :span="20">
                                      <uni-easyinput v-model="ite.value" disabled></uni-easyinput>
                                    </uni-col>
                                    <uni-col :span="4">
                                      <image src="../../static/imgs/del.png" mode="" style="width: 30px; height: 30px"
                                        @click="deleteItem(index,ind)"></image>
                                    </uni-col>
                                  </uni-row>
                                </uni-col>
                              </view>

                            </uni-row>
                          </uni-col>
                        </uni-row>
                      </uni-col>
                    </uni-row>
                    <uni-row :gutter="40">
                      <uni-col :span="12">
                        <u-form-item label="商品加料">
                          <view class="specifications" @click="addAttribute('2')"> +选择加料 </view>
                        </u-form-item>
                      </uni-col>
                      <uni-col :span="12">
                        <u-form-item label="最多加几种">
                          <uni-easyinput placeholder="不填写时，默认为不限量" type="number" clearable v-model="formData.addonKind">
                            <template #right>
                              <text class="suffix-txt">种</text>
                            </template>
                          </uni-easyinput>
                        </u-form-item>
                      </uni-col>
                    </uni-row>
                    <uni-row v-if="feedingList.length>0">
                      <uni-col :span="24" :offset="3">
                        <uni-row :gutter="20">
                          <uni-col :span="7">
                            <view class="goods-name"> 加料商品名称 </view>
                          </uni-col>
                          <uni-col :span="7">
                            <view class="goods-name"> 价格 </view>
                          </uni-col>
                          <uni-col :span="7">
                            <view class="goods-name"> 最多加几份 </view>
                          </uni-col>
                        </uni-row>
                        <view class="row-bot" v-for="(itemF,indexF) in feedingList" :key="indexF">
                          <uni-row :gutter="20">
                            <uni-col :span="7">
                              <uni-easyinput v-model="itemF.name" disabled></uni-easyinput>
                            </uni-col>
                            <uni-col :span="7">
                              <uni-easyinput v-model="itemF.price" disabled></uni-easyinput>
                            </uni-col>
                            <uni-col :span="7">
                              <uni-easyinput placeholder="不填写时，默认为不限量" type="number" clearable v-model="itemF.num">
                                <template #right>
                                  <text class="suffix-txt">份</text>
                                </template>
                              </uni-easyinput>
                            </uni-col>
                            <uni-col :span="3">
                              <image src="../../static/imgs/del.png" mode="" style="width: 30px; height: 30px"
                                @click="deleteFeeding(indexF)"></image>
                            </uni-col>
                          </uni-row>
                        </view>
                      </uni-col>
                    </uni-row>
                  </view>
                  <view class="info-tit"> 商品图片</view>
                  <view class="form-con">
                    <uni-row :gutter="30">
                      <uni-col :span="24">
                        <view class="special-formitem">
                          <u-form-item label="商品主图" required>
                            <!--  <view class="upload1">
                              <u-upload imageMode="widthFix" :fileList="fileList1" @afterRead="afterRead"
                                @delete="deletePic" @beforeRead="checkPermission" :autoUpload ="false" name="1" :maxCount="1"
                                :previewFullImage="true"></u-upload>
                            </view> -->
                            <uploadImage :initial-images="uploadedImagesOne" @upload-success="handleUpload"
                              @remove="handleRemove" />
                            <view style="color: #999999; font-size: 14px; margin-bottom: 4px">建议尺寸：800*800px，大小不超过3MB
                            </view>
                          </u-form-item>
                        </view>
                      </uni-col>
                      <uni-col :span="24">
                        <view class="special-formitem">
                          <u-form-item label="详情图" required class="img2">
                            <view class="upload1" style="height: 88px;">
                              <view class="image-grid">
                                <view v-for="(item, index) in displayedItems" :key="index" class="image-item">
                                  <!-- 已上传图片：显示预览 + 操作按钮 -->
                                  <template v-if="item.isUploaded">
                                    <image :src="item.url" class="preview-img" mode="aspectFill"
                                      @click.prevent="previewImage(index)"></image>
                                    <view class="action-bar">
                                      <!-- 删除按钮 -->
                                      <u-icon name="trash" class="action-icon delete"
                                        @click="removeImage($event, index)" color="#fff;"></u-icon>
                                      <!-- 左移按钮（第一个禁用） -->
                                      <u-icon name="arrow-left" class="action-icon move" v-if="index != 0"
                                        @click="moveLeft(index)" color="#fff;"></u-icon>
                                      <!-- 右移按钮（最后一个禁用） -->
                                      <u-icon name="arrow-right" class="action-icon move"
                                        v-if="index != uploadedImages.length - 1" @click="moveRight(index)"
                                        color="#fff;"></u-icon>
                                    </view>
                                  </template>

                                  <!-- 未上传占位（添加按钮） -->
                                  <template v-else>
                                    <view class="add-btn" @click="chooseImage" v-if="uploadedImages.length < MAX_COUNT">
                                      <u-icon name="camera-fill" class="add-icon" color="#D3D4D6;" size="26"></u-icon>
                                    </view>
                                  </template>
                                </view>
                              </view>
                              <!--   <u-upload imageMode="widthFix" :fileList="fileList2" @afterRead="afterRead"
                            @delete="deletePic" name="2" :maxCount="6" :previewFullImage="true"></u-upload> -->
                            </view>
                            <view style="color: #999999; font-size: 14px; margin-bottom: 4px">
                              建议尺寸：800*800px，大小不超过3MB，最多上传6张。
                            </view>
                          </u-form-item>
                        </view>
                      </uni-col>

                    </uni-row>
                  </view>
                </template>
                <template v-if="currentStep == 2">
                  <view class="form-con form-det">
                    <view class="tit"> 商品详情 </view>
                    <view class="editor-box">
                      <sp-editor :toolbar-config="{
                      excludeKeys: [
                        'direction',
                        'video',
                        'export',
                        'link',
                        'removeFormat',
                        'date',
                        'lineHeight',
                        'letterSpacing',
                        'listCheck',
                        'color',
                        'backgroundColor',
                        'image'
                      ],
                      iconSize: '18px',
                    }" @init="initEditor" @input="inputOver" @upinImage="upinImage" @overMax="overMax"
                        @addLink="addLink" @exportHtml="exportHtml"></sp-editor>
                    </view>
                  </view>
                </template>
              </u-form>
            </view>
          </scroll-view>
        </view>
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close" v-if="currentStep == 1">取消</button>
            <button class="submit_close" @click="back" v-if="currentStep == 2">上一步</button>
            <button class="submit_btn" @click="submitReq" v-if="currentStep == 2">确认</button>
            <button class="submit_btn" @click="submit" v-if="currentStep == 1">下一步</button>
          </view>
        </view>
        <addPopup v-if="showPopup" :showPopup="showPopup" :titPopup="titPopup" @cancelPopup="cancelPopup"
          @surePopup="surePopup" :listPopup="listPopup" :valuePopup="valuePopup" />
      </view>

    </view>
  </view>
</template>
<script setup>
  import {
    ref,
    watch,
    nextTick,
    computed
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    getTreeCategory,
    updateSassCategoryById,
    addSassCategory,
    getAttributeDefinitions,
    getAddonOptions,
    addSassSpecs,
    findSpecsList,
    addProducts,
    updateProducts,
    getBySpuId
  } from '@/requests/apis/products'
  import {
    uploadImgApi
  } from '@/requests/apis/user'
  import
  addPopup
  from '@/components/addPopup/index.vue'
  import
  uploadImage
  from '@/components/upload-image/index.vue'
  import {
    usePermissionStore
  } from '@/stores/modules/permissions';
  import permision from "@/js_sdk/wa-permission/permission.js"
  const permissionStore = usePermissionStore();
  const editorIns = ref(null)
  let spuId = ref()
  let tit = ref('新增商品')
  let show = ref(false)
  let showPopup = ref(false)
  let titPopup = ref()
  let listPopup = ref([])
  let attributeList = ref([])
  let feedingList = ref([])
  let valuePopup = ref()
  const currentStep = ref(1)
  const checkboxValue1 = ref('')
  const checkboxValue2 = ref('')
  const radiovalue1 = ref(1)
  let formData = ref({
    isPublished: 1,
    deliveryMethod: 0,
    sceneLabel: ['门店自提', '外卖配送']
  })
  const specGroups = ref([])
  const specsRows = ref([])
  let shuxingList = ref([])
  let jialiaoList = ref([])
  let fileList1 = ref([])
  let fileList2 = ref([])
  let range = ref([])

  const uploadedImagesOne = ref([]);
  let categoryList = ref([])
  // 批量填写的临时值
  const batchRetail = ref('') // 零售价
  const batchMarket = ref('') // 市场价
  const batchCost = ref('') // 成本价
  const isInitializing = ref(false); // 标记是否为初始化阶段
  // 控制提示框显示状态
  const isTooltipShow = ref(false)
  const iconRef = ref(null); // 图标元素
  const tooltipRef = ref(null); // 提示框元素
  const tooltipContainer = ref(null); // 容器元素
  // 点击图标：切换提示框显示/隐藏
  const toggleTooltip = () => {
    isTooltipShow.value = !isTooltipShow.value
    isTooltipShows.value = false
  }
  const isTooltipShows = ref(false)
  const toggleTooltips = () => {
    isTooltipShows.value = !isTooltipShows.value
    isTooltipShow.value = false
  }
  // const handlePageClick = (e) => {
  //   isTooltipShow.value = false
  //   isTooltipShows.value = false
  // }
  // 全局点击事件处理函数
  const handleClickOutside = (e) => {
    isTooltipShow.value = false
    isTooltipShows.value = false
  };
  watch(
    () => specGroups.value, // 监听的源（数组本身）
    (newVal, oldVal) => {
      console.log('数组发生变化：');
      console.log('新值：', newVal);
      console.log('旧值：', oldVal);
      console.log(isInitializing.value)
      if (!isInitializing.value) {
        console.log("zouzhelim1")
        show.value = false;
      }
    }, {
      deep: true, // 关键：开启深度监听，捕获内部元素变化
    }
  );
  onLoad(async (e) => {
    console.log(e, '1111111');

    await getCategoryList();

    if (e.spuId) {
      spuId.value = e.spuId;
      tit.value = '编辑商品';
      getDetail(e.spuId);
    }

    getList();
  });
  const checkAlbumPermission = async () => {
    /* #ifdef APP-PLUS */
    try {
      if (plus.os.name === "iOS") {
        // iOS 逻辑（插件文档中，judgeIosPermission返回true/false）
        const hasPermission = permision.judgeIosPermission("photoLibrary");
        if (!hasPermission) {
          await showPermissionGuide();
          return permision.judgeIosPermission("photoLibrary");
        }
        return true;
      } else {
        // 未授权时才请求
        const result = await permision.requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE");
        // uni.showToast({
        //   title: `请求结果${result}`,
        //   icon: "none"
        // });
        console.log("请求结果：", result);
        if (result !== 1) {
          // 显示引导弹窗
          await showPermissionGuide(result === -1);
        }
        return true;
      }
    } catch (err) {
      console.error("权限检查失败：", err);
      uni.showToast({
        title: "权限检查异常",
        icon: "none"
      });
      return false;
    }
    /* #endif */
    return true;
  };
  // 权限引导弹窗
  const showPermissionGuide = (isPermanent = false) => {
    return new Promise((resolve) => {
      const content = isPermanent ?
        "相册权限已被永久拒绝，请前往设置手动开启" :
        "需要相册权限才能使用该功能，是否开启？";
      uni.showModal({
        title: "权限提示",
        content: content,
        confirmText: "去设置",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            // 打开设置页，不等待返回（用户操作后手动关闭设置页）
            permision.gotoAppPermissionSetting();
            // 监听应用回到前台（用户从设置页返回）
            uni.onAppShow(async () => {
              uni.offAppShow(); // 移除监听
              // 强制刷新权限状态（关键）
              await permision.checkPermission("android.permission.READ_EXTERNAL_STORAGE");
              resolve(true); // 让后续代码重新检查
            });
          } else {
            // 用户取消，返回未通过
            resolve(false);
          }
        },
        fail: () => {
          resolve(false);
        }
      });
    });
  };

  const MAX_COUNT = 6;
  // 已上传图片列表（包含url和上传状态）
  const uploadedImages = ref([]);

  // 计算显示的项目：已上传图片 + 一个未上传占位符（如果未达上限）
  const displayedItems = computed(() => {
    // 复制已上传图片列表
    const items = uploadedImages.value.map(url => ({
      isUploaded: true,
      url
    }));

    // 如果未达上限，添加一个未上传的占位符
    if (uploadedImages.value.length < MAX_COUNT) {
      items.push({
        isUploaded: false
      });
    }

    return items;
  });

  // 选择图片（唤起相册）
  const chooseImage = async () => {
    console.log("走这里吗222222222")
    const remain = MAX_COUNT - uploadedImages.value.length;
    if (remain <= 0) return; // 已达上限，不再允许上传
    // 2. 权限校验（仅 App 端需要，H5/小程序由系统自动处理）
    // const hasPermission = await checkAlbumPermission();
    // console.log(hasPermission, 'hasPermissionhasPermission')
    // if (!hasPermission) {
    //   return; // 权限未通过，终止流程
    // }
    uni.chooseImage({
      count: remain,
      sizeType: ['compressed'], // 压缩图片，避免过大
      success: async (res) => {
        console.log(res, '0000000000000')
        try {
          // 显示加载提示
          uni.showLoading({
            title: '加载中...',
            mask: true,
          })

          // 循环上传每张图片
          for (const tempFilePath of res.tempFilePaths) {
            // // 调用后端上传接口
            const fileRes = await uni.getFileInfo({
              filePath: tempFilePath
            });
            console.log(fileRes, 'fileRes')
            // 检查文件大小 102771
            if (fileRes.size > 3 * 1024 * 1024) {
              uni.showToast({
                title: '图片大小不能超过3MB',
                icon: 'none'
              });
              continue;
            }

            // 调用后端API上传图片
            console.log(tempFilePath, 'tempFilePath')
            const uploadRes = await uploadImgApi({
              url: tempFilePath,
              thumb: tempFilePath,
              name: 'file',
              type: "image",
              size: fileRes.size
            });
            console.log(uploadRes, 'uploadRes')

            // 假设接口返回格式为 { code: 200, data: { url: '图片URL' } }
            if (uploadRes.ResponseCode === 1) {
              // 上传成功，添加到已上传列表
              uploadedImages.value.push(uploadRes.Result);
            } else {
              uni.showToast({
                title: '上传失败，请重试',
                icon: 'error'
              });
            }
          }
        } catch (error) {
          console.error('图片上传失败:', error);
        } finally {
          uni.hideLoading()
        }
      }
    });
  };

  // 删除图片
  const removeImage = (index) => {
    uploadedImages.value.splice(index, 1);
  };

  // 左移图片（和前一个交换）
  const moveLeft = (index) => {
    if (index > 0) {
      // 添加交换动画效果
      [uploadedImages.value[index], uploadedImages.value[index - 1]] = [uploadedImages.value[index - 1],
        uploadedImages.value[index]
      ];
    }
  };

  // 右移图片（和后一个交换）
  const moveRight = (index) => {
    if (index < uploadedImages.value.length - 1) {
      // 添加交换动画效果
      [uploadedImages.value[index], uploadedImages.value[index + 1]] = [uploadedImages.value[index + 1],
        uploadedImages.value[index]
      ];
    }
  };

  // 预览图片
  const previewImage = (index) => {
    uni.previewImage({
      current: index, // 当前显示图片的索引
      urls: uploadedImages.value, // 需要预览的图片链接列表
      loop: false // 是否可循环预览
    });
  };
  const handleUpload = (imageUrl) => {
    console.log("上传成功")
    uploadedImagesOne.value[0] = imageUrl
  };

  // 处理删除事件
  const handleRemove = (removedUrl) => {
    uploadedImagesOne.value = []
  };

  const getList = async () => {
    let res = await getAttributeDefinitions({
      page: 1,
      limit: 1000,
      status: 1
    })
    shuxingList.value = res.Result.records || [];
    let res2 = await getAddonOptions({
      page: 1,
      limit: 1000,
      keyword: '',
      status: 1
    })
    jialiaoList.value = res2.Result.records || [];
  }
  const isCategoryIdExist = (categoryList, targetId) => {
    for (const item of categoryList) {
      if (item.categoryId === targetId) {
        return true;
      }
      if (item.children && item.children.length > 0) {
        if (isCategoryIdExist(item.children, targetId)) {
          return true;
        }
      }
    }
    // 遍历完所有项都没找到，返回false
    return false;
  };
  const getDetail = async (spuId) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    let res = await getBySpuId({
      spuId
    })
    let data = res.Result;
    formData.value.spuId = data.spuId
    formData.value.oldSpuId = data.spuId
    formData.value.name = data.name
    formData.value.name = data.name
    // formData.value.categoryId = data.categoryId
    const targetId = data.categoryId;
    console.log(categoryList.value, 'categoryList.value')
    if (isCategoryIdExist(categoryList.value, targetId)) {
      formData.value.categoryId = targetId;
    } else {
      formData.value.categoryId = undefined
    }
    formData.value.sortOrder = data.sortOrder ? data.sortOrder : ''
    formData.value.sceneLabel = data.sceneLabel
    formData.value.deliveryMethod = data.deliveryMethod
    formData.value.isPublished = data.isPublished
    formData.value.productionTime = data.productionTime ? data.productionTime : ''
    formData.value.retailPrice = data.retailPrice
    formData.value.marketPrice = data.marketPrice
    formData.value.costPrice = data.costPrice
    formData.value.addonKind = data.addonKind
    formData.value.description = data.description
    console.log(data, 'data')
    // 规格
    if (data.specs) {
      isInitializing.value = true;
      specGroups.value = data.specs.map(spec => ({
        specName: spec.name,
        specValues: spec.specValues.map(item => item.value),
        tempValue: ''
      }));
      nextTick(() => {
        isInitializing.value = false;
      });
      console.log(specGroups.value, 'specGroups.value')
    }
    // 笛卡尔积
    if (data.skusList) {
      specsRows.value = data.skusList
      show.value = true
    }

    // 加料
    if (data.addonDtoList) {
      feedingList.value = data.addonDtoList
    }
    // 属性
    if (data.attributeDtoList) {
      attributeList.value = data.attributeDtoList
    }
    if (data?.mainImage) {
      uploadedImagesOne.value[0] = data.mainImage;
    }
    if (data?.introImages) {
      const arr = data.introImages.split(',')
      uploadedImages.value = arr;
    }
    uni.hideLoading()
  }
  const addAttribute = (type) => {
    if (type == '1') {
      let arr = []
      attributeList.value.forEach((item) => {
        arr.push(item.definitionId)
      })
      valuePopup.value = arr
      listPopup.value = JSON.parse(JSON.stringify(shuxingList.value))
    } else {
      let arr = []
      feedingList.value.forEach((item) => {
        arr.push(item.id)
      })
      valuePopup.value = arr
      listPopup.value = jialiaoList.value
    }
    showPopup.value = true
    titPopup.value = type
  }
  // 添加新的规格组
  const addSpecGroup = () => {
    specGroups.value.push({
      specName: '',
      specValues: [],
      tempValue: '',
    })
  }
  // 删除规格组
  const removeSpecGroup = (groupIndex) => {
    console.log('removeSpecGroup')
    specGroups.value.splice(groupIndex, 1)
  }
  // 添加规格值（去重校验）
  const addSpecValue = (groupIndex) => {
    const group = specGroups.value[groupIndex]
    const value = group.tempValue.trim()
    if (!value)
      return uni.showToast({
        title: '请输入有效规格值',
        icon: 'none',
      })
    if (group.specValues.includes(value))
      return uni.showToast({
        title: '该规格值已存在',
        icon: 'none',
      })

    group.specValues.push(value)
    group.tempValue = ''
  }

  // 删除单个规格值
  const removeSpecValue = (groupIndex, valueIndex) => {
    specGroups.value[groupIndex].specValues.splice(valueIndex, 1)
  }
  const generateSpecs = async () => {

    let res = await addSassSpecs({
      specs: specGroups.value
    })
    if (res) {
      let _res = await findSpecsList({
        specs: specGroups.value
      })
      console.log(_res.Result, '_res_res_res_res')
      specsRows.value = generateSpecCombinations(_res.Result)
      console.log('生成的规格数据：', specsRows.value) // 可查看控制台结构

      show.value = true
    }

  }
  // 生成笛卡尔积
  const generateSpecCombinations = (groups) => {
    if (groups.length === 0) return [];
    let combinations = groups[0].specValues.map(option => [{
      ...option,
      name: groups[0].name
    }]);
    for (let i = 1; i < groups.length; i++) {
      const temp = [];
      for (const combo of combinations) {
        for (const option of groups[i].specValues) {
          temp.push([
            ...combo,
            {
              ...option,
              name: groups[i].name
            }
          ]);
        }
      }
      combinations = temp;
    }
    return combinations.map(specItems => ({
      specValueDtoList: specItems,
      sku: '',
      retailPrice: '',
      marketPrice: '',
      costPrice: ''
    }));
  };
  // 批量填写逻辑：将批量值赋给所有规格行
  const batchFill = () => {
    specsRows.value.forEach((row) => {
      row.retailPrice = batchRetail.value
      row.marketPrice = batchMarket.value
      row.costPrice = batchCost.value
    })
  }
  // 商品属性 商品加料 确定
  const surePopup = (type, checkboxData) => {
    showPopup.value = false
    console.log(checkboxData, 'checkboxData', type)
    // 属性
    if (type == '1') {
      // const invalidGoods = shuxingList.value.filter(item =>
      //   checkboxData.includes(item.definitionId)
      // );
      // //
      // console.log(invalidGoods,'invalidGoodsinvalidGoods')
      // attributeList.value = invalidGoods
      attributeList.value = shuxingList.value
        .filter(item => checkboxData.includes(item.definitionId)) // 先过滤
        .map(item => JSON.parse(JSON.stringify(item))); // 对每个元素深拷贝
    } else {
      const invalidGoods = jialiaoList.value.filter(item =>
        checkboxData.includes(item.id)
      );
      feedingList.value = invalidGoods;
      feedingList.value.forEach(item => {
        item['num'] = ''
      })
    }
  }
  const delelGroups = (index) => {
    specsRows.value.splice(index, 1);
  }
  // 删除商品加料
  const deleteFeeding = (index) => {
    feedingList.value.splice(index, 1);
  }
  // 删除商品属性
  const deleteItem = (attrIdx, valIdx) => {
    attributeList.value[attrIdx].attributeValue.splice(valIdx, 1);
    if (attributeList.value[attrIdx].attributeValue.length === 0) {
      attributeList.value.splice(attrIdx, 1);
    }
  }
  // 将扁平化数据还原为原始嵌套格式
  const restoreOriginalFormat = () => {
    const groupMap = {}

    flatList.value.forEach((item) => {
      const {
        definitionId,
        name,
        valueId,
        value
      } = item
      if (!groupMap[definitionId]) {
        groupMap[definitionId] = {
          definitionId,
          name,
          attributeValue: [],
        }
      }
      // 添加属性值
      groupMap[definitionId].attributeValue.push({
        definitionId,
        definitionValueId: valueId,
        value,
      })
    })
    return Object.values(groupMap)
  }
  const cancelPopup = (type) => {
    showPopup.value = false
  }
  // 递归转换函数
  const transformData = (list) => {
    return list.map((item) => {
      const transformed = {
        text: item.categoryName,
        value: item.categoryId,
      }
      if (item.children && item.children.length > 0) {
        transformed.children = transformData(item.children)
      }
      return transformed
    })
  }
  // 获取上级分类数据
  const getCategoryList = async () => {
    let res = await getTreeCategory({
      isActive: 1
    })
    categoryList.value = res.Result || []
    console.log(categoryList.value, 'categoryListcategoryListcategoryListcategoryListcategoryListcategoryList')
    let arr = res.Result || []
    const arr2 = transformData(arr)
    range.value = arr2
  }
  const checkPermission = async (file, lists, name) => {
    console.log("走这里吗11111111111111")
    // 1. 权限校验（如相册/相机权限）
    const hasPermission = await checkAlbumPermission(); // 调用你的权限校验方法
    if (!hasPermission) {
      return false; // 无权限，阻止选择
    }

    // 允许选择（返回true或不返回）
    return true;
  };

  const afterRead = async (e) => {
    console.log(e, '1111111111')
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    const res = await uploadImgApi(e.file)
    console.log(res, '1111111111')
    uni.hideLoading()
    if (res) {
      if (e.name === '1') {
        fileList1.value.push({
          type: 'image',
          status: 'success',
          url: res.Result,
        })
      } else {
        fileList2.value.push({
          type: 'image',
          status: 'success',
          url: res.Result,
        })
      }
    }
  }
  const deletePic = (e) => {
    if (e.name === '1') {
      fileList1.value.splice(e.index, 1)
    } else {
      fileList2.value.splice(e.index, 1)
    }
  }

  // 转换为后端需要的 skus 格式
  const convertToSkus = () => {
    const skus = specsRows.value.map(row => {
      return {
        specValueId: row.specValueDtoList.map(item => item.specValueId),
        retailPrice: Number(row.retailPrice) || null,
        marketPrice: Number(row.marketPrice) || null,
        costPrice: Number(row.costPrice) || null,
        skuId: row.skuId

      };
    });

    return skus;
  };

  const back = () => {
    currentStep.value = 1
  }


  // const submit = () => {
  //   console.log(displayedItems, 'displayedItems', 'uploadedImages', uploadedImages.value)
  //   const valid = [{
  //       k: 'name',
  //       err: '请输入商品名称',
  //     },
  //     {
  //       k: 'categoryId',
  //       err: '请选择商品分类',
  //     },
  //     {
  //       k: 'sceneLabel',
  //       err: '请选择发布场景',
  //     },
  //     {
  //       k: 'deliveryMethod',
  //       err: '请选择配送方式',
  //     }
  //   ]
  //   let err = ''
  //   const priceReg = /^\d+(\.\d{1,2})?$/;
  //   for (let item of valid) {
  //     if (!formData.value[item.k] && formData.value[item.k] !== 0) {
  //       err = item.err
  //       break
  //     }
  //   }
  //   if (formData.value.spuId) {
  //     const reg = /^[a-zA-Z0-9]+$/;
  //     if (!reg.test(formData.value.spuId)) {
  //       err = '商品编码只能输入 字母，数字'
  //     }
  //   }
  //   if (specGroups.value.length <= 0) {
  //     console.log("111111111111", formData.value.retailPrice)
  //     // if (!formData.value.retailPrice) {
  //     //   err = '请输入零售价'
  //     // }
  //     // 1. 零售价：必填 + 格式校验
  //     const retailPrice = String(formData.value.retailPrice || '').trim();
  //     if (retailPrice === '') {
  //       err = '请输入零售价';
  //     } else if (!priceReg.test(retailPrice)) {
  //       err = '零售价必须为整数或两位小数';
  //     }
  //     // 2. 成本价
  //     const costPrice = String(formData.value.costPrice || '').trim();
  //     if (costPrice !== '' && !priceReg.test(costPrice)) {
  //       err = '成本价必须为整数或两位小数';
  //     }
  //     // 3. 市场价
  //     const marketPrice = String(formData.value.marketPrice || '').trim();
  //     if (marketPrice !== '' && !priceReg.test(marketPrice)) {
  //       err = '市场价必须为整数或两位小数';
  //     }
  //   } else {
  //     if (specsRows.value.length <= 0) {
  //       err = '请点击一键生成规格明细去填写'
  //     } else {
  //       const reg = /^[a-zA-Z0-9]+$/;
  //       for (const row of specsRows.value) {
  //         if (!row.skuId) continue;
  //         // 验证不通过
  //         if (!reg.test(row.skuId)) {
  //           err = 'SKU编码只能输入 字母，数字'

  //         }
  //       }
  //     }
  //   }
  //   if (!fileList1.value?.length) {
  //     err = '请上传商品主图'
  //   }
  //   if (!uploadedImages.value?.length) {
  //     err = '请上传商品详情图'
  //   }
  //   // for (const item of specsRows.value) {
  //   //   if (item.retailPrice === '') {
  //   //     err = '请输入零售价'
  //   //     break
  //   //   }
  //   // }



  //   for (const item of specsRows.value) {
  //     // 1. 零售价（必填，支持整数或两位小数）
  //     const retailPrice = String(item.retailPrice || '').trim();
  //     if (retailPrice === '') {
  //       err = '请输入零售价';
  //     }
  //     if (!err && !priceReg.test(retailPrice)) {
  //       err = '零售价必须为整数或两位小数';
  //     }

  //     // 2. 市场价（非必填，填写则需符合格式）
  //     const marketPrice = String(item.marketPrice || '').trim();
  //     if (!err && marketPrice !== '' && !priceReg.test(marketPrice)) {
  //       err = '市场价必须为整数或两位小数';
  //     }

  //     // 3. 成本价（非必填，填写则需符合格式）
  //     const costPrice = String(item.costPrice || '').trim();
  //     if (!err && costPrice !== '' && !priceReg.test(costPrice)) {
  //       err = '成本价必须为整数或两位小数';
  //     }
  //   }

  //   console.log(typeof(formData.value.addonKind), 'formData.value.addonKind')
  //   if (formData.value.addonKind !== undefined && formData.value.addonKind !== null && formData.value.addonKind !==
  //     '') {
  //     const addonKindVal = Number(formData.value.addonKind);
  //     console.log(addonKindVal, 'addonKindVal')
  //     if (addonKindVal === 0) {
  //       err = "商品加料种类不能为0"
  //     }
  //   }

  //   for (const item of feedingList.value) {
  //     if (item.num !== '' && item.num !== undefined && item.num !== null) {
  //       const numVal = Number(item.num);
  //       if (numVal === 0) {
  //         err = "商品加料份数不能为0"
  //       }
  //     }
  //   }
  //   if (err) {
  //     uni.showToast({
  //       title: err,
  //       duration: 2000,
  //       icon: 'none',
  //     })
  //   } else {
  //     currentStep.value = 2
  //   }
  // }
  const submit = () => {
    console.log(displayedItems, 'displayedItems', 'uploadedImages', uploadedImages.value);
    let err = '';
    const priceReg = /^\d+(\.\d{1,2})?$/;

    // 验证「顶部必填项」（商品名称、分类、发布场景、配送方式）
    const topRequired = [{
        k: 'name',
        err: '请输入商品名称'
      },
      {
        k: 'categoryId',
        err: '请选择商品分类'
      },
      {
        k: 'sceneLabel',
        err: '请选择发布场景'
      },
      {
        k: 'deliveryMethod',
        err: '请选择配送方式'
      }
    ];
    if (formData.value.spuId) {
      const spuReg = /^[a-zA-Z0-9]+$/;
      if (!spuReg.test(formData.value.spuId)) {
        err = '商品编码只能输入字母、数字';
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }
    }

    for (const item of topRequired) {
      if (!formData.value[item.k] && formData.value[item.k] !== 0) {
        err = item.err;
        break;
      }
    }
    if (err) {
      uni.showToast({
        title: err,
        duration: 2000,
        icon: 'none'
      });
      return;
    }
    // 3.1 零售价（必填 + 格式）
    const retailPrice = String(formData.value.retailPrice || '').trim();
    if (specGroups.value.length <= 0) {
      if (retailPrice === '') {
        err = '请输入零售价';
      } else if (!priceReg.test(retailPrice)) {
        err = '零售价必须为整数或两位小数';
      }
      if (err) {
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }

      // 3.2 市场价（选填 + 格式）
      const marketPrice = String(formData.value.marketPrice || '').trim();
      if (marketPrice !== '' && !priceReg.test(marketPrice)) {
        err = '市场价必须为整数或两位小数';
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }

      // 3.3 成本价（选填 + 格式）
      const costPrice = String(formData.value.costPrice || '').trim();
      if (costPrice !== '' && !priceReg.test(costPrice)) {
        err = '成本价必须为整数或两位小数';
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }
    } else {
      // 验证「商品规格」
      //  规格行是否存在
      if (specsRows.value.length <= 0) {
        err = '请点击一键生成规格明细去填写';
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }

      // SKU编码格式
      const skuReg = /^[a-zA-Z0-9]+$/;
      for (const row of specsRows.value) {
        if (!row.skuId) continue;
        if (!skuReg.test(row.skuId)) {
          err = 'SKU编码只能输入字母、数字';
          break;
        }
      }
      if (err) {
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }

      // 规格行的价格（零售价、市场价、成本价）
      for (const item of specsRows.value) {
        // 规格行零售价（必填 + 格式）
        const rowRetail = String(item.retailPrice || '').trim();
        if (rowRetail === '') {
          err = '请输入零售价';
          break;
        }
        if (!priceReg.test(rowRetail)) {
          err = '零售价必须为整数或两位小数';
          break;
        }

        // 规格行市场价（选填 + 格式）
        const rowMarket = String(item.marketPrice || '').trim();
        if (rowMarket !== '' && !priceReg.test(rowMarket)) {
          err = '市场价必须为整数或两位小数';
          break;
        }

        // 规格行成本价（选填 + 格式）
        const rowCost = String(item.costPrice || '').trim();
        if (rowCost !== '' && !priceReg.test(rowCost)) {
          err = '成本价必须为整数或两位小数';
          break;
        }
      }
      if (err) {
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }
    }

    const integerReg = /^\d+$/;
    //验证「商品加料种类」
    if (formData.value.addonKind !== undefined && formData.value.addonKind !== null && formData.value.addonKind !==
      '') {
      if (!integerReg.test(formData.value.addonKind)) {
        err = '商品加料种类必须为整数';
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }
      const addonKindVal = Number(formData.value.addonKind);
      if (addonKindVal === 0) {
        err = '商品加料种类不能为0';
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }
    }

    // 验证「商品加料份数
    for (const item of feedingList.value) {
      if (item.num !== '' && item.num !== undefined && item.num !== null) {
        if (!integerReg.test(item.num)) {
          err = '商品加料份数必须为整数';
          uni.showToast({
            title: err,
            duration: 2000,
            icon: 'none'
          });
          return;
        }
        const numVal = Number(item.num);
        if (numVal === 0) {
          err = '商品加料份数不能为0';
          uni.showToast({
            title: err,
            duration: 2000,
            icon: 'none'
          });
          return;
        }
      }
    }

    //  验证「商品主图
    if (!uploadedImagesOne.value?.length) {
      err = '请上传商品主图';
      uni.showToast({
        title: err,
        duration: 2000,
        icon: 'none'
      });
      return;
    }

    //验证「商品详情图」
    if (!uploadedImages.value?.length) {
      err = '请上传商品详情图';
      uni.showToast({
        title: err,
        duration: 2000,
        icon: 'none'
      });
      return;
    }

    currentStep.value = 2;
  };
  const submitReq = async () => {

    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    console.log(feedingList.value, 'feedingListfeedingList')
    console.log(attributeList.value, 'attributeListattributeList')
    console.log(specsRows, 'specsRows')
    let skus = convertToSkus();
    console.log('转换后的 skus：', skus);
    let attributes = []; //属性
    let addonForms = []; //加料
    attributeList.value.forEach(item => {
      item.attributeValue.forEach(attr => {
        attributes.push(Number(attr.definitionValueId));
      });
    });
    feedingList.value.forEach(item => {
      addonForms.push({
        id: item.id,
        name: item.name,
        num: item.num ? Number(item.num) : null
      });
    });
    console.log(attributes, 'attributes', addonForms, 'addonForms')
    let postData = JSON.parse(JSON.stringify(formData.value))
    postData.sortOrder = Number(postData.sortOrder) != 0 ? Number(postData.sortOrder) : undefined
    postData.productionTime = Number(postData.productionTime) != 0 ? Number(postData.productionTime) : undefined
    postData.addonKind = postData.addonKind ? Number(postData.addonKind) : null
    // postData.deliveryMethod = postData.deliveryMethod
    postData.mainImage = uploadedImagesOne.value
      .map((item) => {
        return item
      })
      .join(',')
    postData.introImages = uploadedImages.value
      .map((item) => {
        return item
      })
      .join(',')
    postData.attributes = attributes
    postData.addonForms = addonForms
    postData.skus = skus
    console.log(postData, 'POSTPOST')
    const fn = spuId.value ? updateProducts : addProducts
    try {
      const res = await fn(postData)
      console.log(res, 'resres')
      uni.hideLoading()
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 800)
    } catch (error) {
      console.log(error)
    }
  }
  const close = () => {
    uni.navigateBack()
  }

  function inputOver(e) {
    // 可以在此处获取到编辑器已编辑的内容
    formData.value.description = e.html
  }

  /**
   * 超出最大内容限制
   * @param {Object} e {html,text} 内容的html文本，和text文本
   */
  function overMax(e) {
    // 若设置了最大字数限制，可在此处触发超出限制的回调
    console.log('==== overMax :', e)
  }

  /** 编辑器就绪*/
  function initEditor(editor) {
    editorIns.value = editor
    preRender()
  }

  function preRender() {
    // 异步获取后端数据后，初始化编辑器内容
    editorIns.value.setContents({
      html: formData.value.description,
    })
  }

  //上传图片
  const upinImage = async (tempFiles, editorCtx) => {
    console.log(tempFiles, 'tempFiles')
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    let res = await uploadImgApi({
      name: "",
      size: tempFiles[0].size,
      thumb: tempFiles[0].tempFilePath,
      type: tempFiles[0].fileType,
      url: tempFiles[0].tempFilePath,
    })
    if (res) {
      uni.hideLoading()
      editorCtx.insertImage({
        src: res.Result,
        width: '80%',
        success: function() {
          uni.hideLoading()
        }
      })
    }

  }

  //导出 - toolbar需要开启export工具
  function exportHtml(e) {
    uni.navigateTo({
      url: '/pages/out/out',
      success(res) {
        // 传至导出页面解析即可
        res.eventChannel.emit('e-transmit-html', {
          data: e,
        })
      },
    })
  }
</script>
<style lang="scss" scoped>
  .upload1 {

    .u-upload__button,
    image {
      width: 80px !important;
      height: 80px !important;
    }
  }

  .image-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;

    // 图片项：固定尺寸，统一边框
    .image-item {
      width: 80px;
      height: 80px;
      position: relative;
      background-color: rgb(244, 245, 247);
      border-radius: 2px;
      overflow: hidden;

      // 预览图样式
      .preview-img {
        width: 100%;
        height: 100%;
      }

      // 操作栏：底部半透明背景
      .action-bar {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        // height: 60rpx;
        background: rgba(0, 0, 0, 0.2);
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 0 10px;
        box-sizing: border-box;

        // 操作图标通用样式
        .action-icon {
          color: #fff;
          font-size: 30rpx;
        }

        // 删除图标单独间距
        .delete {
          margin-right: 10rpx;
        }

        // 禁用状态样式
        .move:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }

      // 添加按钮：居中显示加号
      .add-btn {
        width: 100%;
        height: 100%;
        background-color: rgb(244, 245, 247);
        display: flex;
        justify-content: center;
        align-items: center;

        .add-icon {
          font-size: 26px;
          line-height: 26px;
          color: #D3D4D6;
        }
      }
    }
  }


  .form-container {
    // padding: 0 100px;
  }

  .goods-container {
    width: 100%;
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    display: flex;
    flex-direction: column;

    .form-con {
      padding: 0 100px;

      .flex-label {
        flex: 1;
      }

      .direction-container {
        display: flex;
        align-items: center;
        margin-left: 8px;

        .item {
          position: relative;

          .tooltip-box {
            width: 160px;
            position: absolute;
            left: 50%;
            top: calc(100% + 6px);
            transform: translateX(-50%);
            background: rgba(47, 75, 153, 0.8);
            font-size: 14px;
            color: #fff;
            box-sizing: border-box;
            padding: 8px;
            border-radius: 6px;
            z-index: 9999;
            display: none;

            &.show {
              display: block;
            }
          }

          .tooltip-arrow {
            position: absolute;
            top: -6px;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            border-top: 6px solid rgba(47, 75, 153, 0.8);
            border-bottom: 6px solid rgba(47, 75, 153, 0.8);
            border-top: none;
          }
        }
      }

      .icon-con {
        width: 14px;
        height: 14px;
        vertical-align: middle;
        cursor: pointer;
      }

      :deep(.u-form-item__body__right__content__slot) {
        flex-direction: column !important;
        align-items: baseline !important;
      }

      .row-bot {
        :deep(.uni-row) {
          margin-bottom: 10px;
        }

        :deep(.is-disabled) {
          color: #666 !important;
          background: #F6F6F6 !important;
        }
      }

      .marg-col {
        :deep(.uni-col) {
          margin-bottom: 10px;
        }
      }

      .suffix-txt {
        background: #f5f6f8;
        border-left: 1px solid #e8ecef;
        font-weight: 400;
        font-size: 14px;
        color: #334681;
        padding: 6px 16px;
        box-sizing: border-box;
      }

      .suffix-num {
        font-weight: 400;
        font-size: 14px;
        color: rgba(51, 70, 129, 0.6);
        padding-right: 5px;
        box-sizing: border-box;
      }

      .specifications {
        background: #0f90fd;
        border-radius: 8px;
        font-weight: 400;
        font-size: 14px;
        color: #ffffff;
        padding: 7px 27px;
        box-sizing: border-box;
      }

      .spec-group {
        background: #f7f9fa;
        border-radius: 10px;
        border: 1px solid #e8ecef;
        padding: 10px 20px;
        box-sizing: border-box;
        margin-bottom: 10px;

        .del-btn {
          position: sticky;
          z-index: 99;

          :deep(.u-button) {
            float: right;
          }
        }
      }

      :deep(.u-button) {
        height: 32px;
        width: 100px;
        margin-left: 10px;
      }

      .generate-btn {
        display: flex;
        justify-content: center;
        margin: 17px 0;
      }

      .goods-name {
        font-weight: 400;
        font-size: 14px;
        color: #333333;
        margin-bottom: 4px;
      }
    }

    .form-det {
      display: flex;

      .tit {
        width: 100px;
        color: #303133;
        font-size: 15px;
      }

      .editor-box {
        border: 1px solid #e8e8e8;
        width: 100%;
        height: 400px;
      }
    }

    .info-tit {
      font-weight: 500;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
      padding-left: 57px;
      box-sizing: border-box;
    }

    .step-nav {
      display: flex;
      align-items: center;
      margin: 20px;
      justify-content: center;
    }

    .step-item {
      position: relative;
      padding: 0 20px;
      line-height: 32px;
      font-size: 14px;
      color: #333;
      background: #f5f5f5;
      transition: all 0.3s;
    }

    /* 激活状态样式 */
    .step-item.active {
      background: #0f90fd;
      color: #fff;
      border-color: #0f90fd;
    }

    /* 箭头实现：每个步骤（除最后一个）右侧生成箭头 */
    .step-item:not(:last-child)::after {
      content: '';
      position: absolute;
      top: 0;
      right: -16px;
      width: 0;
      height: 0;
      border-top: 16px solid transparent;
      border-bottom: 16px solid transparent;
      border-left: 16px solid #0f90fd;
      z-index: 2;
    }

    .step-item:not(.active)::after {
      border-left-color: #f5f5f5;
    }

    .step-item:first-child {
      border-top-left-radius: 6px;
      border-bottom-left-radius: 6px;
    }

    .step-item:last-child {
      border-top-right-radius: 6px;
      border-bottom-right-radius: 6px;
    }
  }

  .submit_btncon {
    margin-top: auto;
    position: static;
    bottom: 0;
    // width: 71vw;
    background: #ffffff;
    box-shadow: 0px -2px 4px 0px rgba(51, 70, 129, 0.1);
    border-radius: 10px 10px 0px 0px;
    padding: 13px 0;
    // box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;

    button {
      padding: 0 46px;
      height: 34px;
      box-sizing: border-box;
      border-radius: 8px;
      margin: 0 10px;

      &:after {
        border: none;
      }
    }

    .submit_btn {
      background: #0f90fd;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
    }

    .submit_close {
      background: #eeeeee;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
    }
  }

  /* 预览列表 */
  .preview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-top: 10px;
    width: 100%;
  }

  .preview-item {
    position: relative;
    /* 用于操作按钮绝对定位 */
    width: 60px;
    height: 60px;
  }

  .preview-img {
    width: 100%;
    height: 100%;
    border-radius: 4px;
  }

  /* 操作按钮：覆盖在图片底部 */
  .operate-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: space-around;
    padding: 5px 0;
  }

  .operate-icon {
    color: #fff;
    font-size: 12px;
  }
</style>
